Add MW_REST_API and MW_ENTRY_POINT
[lhc/web/wiklou.git] / includes / Setup.php
1 <?php
2 /**
3 * Include most things that are needed to make MediaWiki work.
4 *
5 * This file is included by WebStart.php and doMaintenance.php so that both
6 * web and maintenance scripts share a final set up phase to include necessary
7 * files and create global object variables.
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26 use MediaWiki\MediaWikiServices;
27 use Wikimedia\Rdbms\LBFactory;
28 use Wikimedia\Rdbms\ChronologyProtector;
29
30 /**
31 * This file is not a valid entry point, perform no further processing unless
32 * MEDIAWIKI is defined
33 */
34 if ( !defined( 'MEDIAWIKI' ) ) {
35 exit( 1 );
36 }
37
38 // Check to see if we are at the file scope
39 $wgScopeTest = 'MediaWiki Setup.php scope test';
40 if ( !isset( $GLOBALS['wgScopeTest'] ) || $GLOBALS['wgScopeTest'] !== $wgScopeTest ) {
41 echo "Error, Setup.php must be included from the file scope.\n";
42 die( 1 );
43 }
44 unset( $wgScopeTest );
45
46 /**
47 * Pre-config setup: Before loading LocalSettings.php
48 */
49
50 // Sanity check (T5782, T122807)
51 if ( ini_get( 'mbstring.func_overload' ) ) {
52 die( 'MediaWiki does not support installations where mbstring.func_overload is non-zero.' );
53 }
54
55 // Define MW_ENTRY_POINT if it's not already, so that config code can check the
56 // value without using defined()
57 if ( !defined( 'MW_ENTRY_POINT' ) ) {
58 /**
59 * The entry point, which may be either the script filename without the
60 * file extension, or "cli" for maintenance scripts, or "unknown" for any
61 * entry point that does not set the constant.
62 */
63 define( 'MW_ENTRY_POINT', 'unknown' );
64 }
65
66 // Start the autoloader, so that extensions can derive classes from core files
67 require_once "$IP/includes/AutoLoader.php";
68
69 // Load global constants
70 require_once "$IP/includes/Defines.php";
71
72 // Load default settings
73 require_once "$IP/includes/DefaultSettings.php";
74
75 // Load global functions
76 require_once "$IP/includes/GlobalFunctions.php";
77
78 // Load composer's autoloader if present
79 if ( is_readable( "$IP/vendor/autoload.php" ) ) {
80 require_once "$IP/vendor/autoload.php";
81 } elseif ( file_exists( "$IP/vendor/autoload.php" ) ) {
82 die( "$IP/vendor/autoload.php exists but is not readable" );
83 }
84
85 // Assert that composer dependencies were successfully loaded
86 // Purposely no leading \ due to it breaking HHVM RepoAuthorative mode
87 // PHP works fine with both versions
88 // See https://github.com/facebook/hhvm/issues/5833
89 if ( !interface_exists( 'Psr\Log\LoggerInterface' ) ) {
90 $message = (
91 'MediaWiki requires the <a href="https://github.com/php-fig/log">PSR-3 logging ' .
92 "library</a> to be present. This library is not embedded directly in MediaWiki's " .
93 "git repository and must be installed separately by the end user.\n\n" .
94 'Please see <a href="https://www.mediawiki.org/wiki/Download_from_Git' .
95 '#Fetch_external_libraries">mediawiki.org</a> for help on installing ' .
96 'the required components.'
97 );
98 echo $message;
99 trigger_error( $message, E_USER_ERROR );
100 die( 1 );
101 }
102
103 /**
104 * Changes to the PHP environment that don't vary on configuration.
105 */
106
107 // Install a header callback
108 MediaWiki\HeaderCallback::register();
109
110 // Set the encoding used by PHP for reading HTTP input, and writing output.
111 // This is also the default for mbstring functions.
112 mb_internal_encoding( 'UTF-8' );
113
114 /**
115 * Load LocalSettings.php
116 */
117
118 if ( defined( 'MW_CONFIG_CALLBACK' ) ) {
119 call_user_func( MW_CONFIG_CALLBACK );
120 } else {
121 if ( !defined( 'MW_CONFIG_FILE' ) ) {
122 define( 'MW_CONFIG_FILE', "$IP/LocalSettings.php" );
123 }
124 require_once MW_CONFIG_FILE;
125 }
126
127 /**
128 * Customization point after all loading (constants, functions, classes,
129 * DefaultSettings, LocalSettings). Specifically, this is before usage of
130 * settings, before instantiation of Profiler (and other singletons), and
131 * before any setup functions or hooks run.
132 */
133
134 if ( defined( 'MW_SETUP_CALLBACK' ) ) {
135 call_user_func( MW_SETUP_CALLBACK );
136 }
137
138 /**
139 * Main setup
140 */
141
142 // Load queued extensions
143 ExtensionRegistry::getInstance()->loadFromQueue();
144 // Don't let any other extensions load
145 ExtensionRegistry::getInstance()->finish();
146
147 // Set the configured locale on all requests for consisteny
148 putenv( "LC_ALL=$wgShellLocale" );
149 setlocale( LC_ALL, $wgShellLocale );
150
151 // Set various default paths sensibly...
152 if ( $wgScript === false ) {
153 $wgScript = "$wgScriptPath/index.php";
154 }
155 if ( $wgLoadScript === false ) {
156 $wgLoadScript = "$wgScriptPath/load.php";
157 }
158 if ( $wgRestPath === false ) {
159 $wgRestPath = "$wgScriptPath/rest.php";
160 }
161
162 if ( $wgArticlePath === false ) {
163 if ( $wgUsePathInfo ) {
164 $wgArticlePath = "$wgScript/$1";
165 } else {
166 $wgArticlePath = "$wgScript?title=$1";
167 }
168 }
169
170 if ( !empty( $wgActionPaths ) && !isset( $wgActionPaths['view'] ) ) {
171 // 'view' is assumed the default action path everywhere in the code
172 // but is rarely filled in $wgActionPaths
173 $wgActionPaths['view'] = $wgArticlePath;
174 }
175
176 if ( $wgResourceBasePath === null ) {
177 $wgResourceBasePath = $wgScriptPath;
178 }
179 if ( $wgStylePath === false ) {
180 $wgStylePath = "$wgResourceBasePath/skins";
181 }
182 if ( $wgLocalStylePath === false ) {
183 // Avoid wgResourceBasePath here since that may point to a different domain (e.g. CDN)
184 $wgLocalStylePath = "$wgScriptPath/skins";
185 }
186 if ( $wgExtensionAssetsPath === false ) {
187 $wgExtensionAssetsPath = "$wgResourceBasePath/extensions";
188 }
189
190 if ( $wgLogo === false ) {
191 $wgLogo = "$wgResourceBasePath/resources/assets/wiki.png";
192 }
193
194 if ( $wgUploadPath === false ) {
195 $wgUploadPath = "$wgScriptPath/images";
196 }
197 if ( $wgUploadDirectory === false ) {
198 $wgUploadDirectory = "$IP/images";
199 }
200 if ( $wgReadOnlyFile === false ) {
201 $wgReadOnlyFile = "{$wgUploadDirectory}/lock_yBgMBwiR";
202 }
203 if ( $wgFileCacheDirectory === false ) {
204 $wgFileCacheDirectory = "{$wgUploadDirectory}/cache";
205 }
206 if ( $wgDeletedDirectory === false ) {
207 $wgDeletedDirectory = "{$wgUploadDirectory}/deleted";
208 }
209
210 if ( $wgGitInfoCacheDirectory === false && $wgCacheDirectory !== false ) {
211 $wgGitInfoCacheDirectory = "{$wgCacheDirectory}/gitinfo";
212 }
213
214 // Fix path to icon images after they were moved in 1.24
215 if ( $wgRightsIcon ) {
216 $wgRightsIcon = str_replace(
217 "{$wgStylePath}/common/images/",
218 "{$wgResourceBasePath}/resources/assets/licenses/",
219 $wgRightsIcon
220 );
221 }
222
223 if ( isset( $wgFooterIcons['copyright']['copyright'] )
224 && $wgFooterIcons['copyright']['copyright'] === []
225 ) {
226 if ( $wgRightsIcon || $wgRightsText ) {
227 $wgFooterIcons['copyright']['copyright'] = [
228 'url' => $wgRightsUrl,
229 'src' => $wgRightsIcon,
230 'alt' => $wgRightsText,
231 ];
232 }
233 }
234
235 if ( isset( $wgFooterIcons['poweredby'] )
236 && isset( $wgFooterIcons['poweredby']['mediawiki'] )
237 && $wgFooterIcons['poweredby']['mediawiki']['src'] === null
238 ) {
239 $wgFooterIcons['poweredby']['mediawiki']['src'] =
240 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_88x31.png";
241 $wgFooterIcons['poweredby']['mediawiki']['srcset'] =
242 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_132x47.png 1.5x, " .
243 "$wgResourceBasePath/resources/assets/poweredby_mediawiki_176x62.png 2x";
244 }
245
246 /**
247 * Unconditional protection for NS_MEDIAWIKI since otherwise it's too easy for a
248 * sysadmin to set $wgNamespaceProtection incorrectly and leave the wiki insecure.
249 *
250 * Note that this is the definition of editinterface and it can be granted to
251 * all users if desired.
252 */
253 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
254
255 /**
256 * The canonical names of namespaces 6 and 7 are, as of v1.14, "File"
257 * and "File_talk". The old names "Image" and "Image_talk" are
258 * retained as aliases for backwards compatibility.
259 */
260 $wgNamespaceAliases['Image'] = NS_FILE;
261 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
262
263 /**
264 * Initialise $wgLockManagers to include basic FS version
265 */
266 $wgLockManagers[] = [
267 'name' => 'fsLockManager',
268 'class' => FSLockManager::class,
269 'lockDirectory' => "{$wgUploadDirectory}/lockdir",
270 ];
271 $wgLockManagers[] = [
272 'name' => 'nullLockManager',
273 'class' => NullLockManager::class,
274 ];
275
276 /**
277 * Default parameters for the "<gallery>" tag.
278 * @see DefaultSettings.php for description of the fields.
279 */
280 $wgGalleryOptions += [
281 'imagesPerRow' => 0,
282 'imageWidth' => 120,
283 'imageHeight' => 120,
284 'captionLength' => true,
285 'showBytes' => true,
286 'showDimensions' => true,
287 'mode' => 'traditional',
288 ];
289
290 /**
291 * Shortcuts for $wgLocalFileRepo
292 */
293 if ( !$wgLocalFileRepo ) {
294 $wgLocalFileRepo = [
295 'class' => LocalRepo::class,
296 'name' => 'local',
297 'directory' => $wgUploadDirectory,
298 'scriptDirUrl' => $wgScriptPath,
299 'url' => $wgUploadBaseUrl ? $wgUploadBaseUrl . $wgUploadPath : $wgUploadPath,
300 'hashLevels' => $wgHashedUploadDirectory ? 2 : 0,
301 'thumbScriptUrl' => $wgThumbnailScriptPath,
302 'transformVia404' => !$wgGenerateThumbnailOnParse,
303 'deletedDir' => $wgDeletedDirectory,
304 'deletedHashLevels' => $wgHashedUploadDirectory ? 3 : 0
305 ];
306 }
307
308 if ( !isset( $wgLocalFileRepo['backend'] ) ) {
309 // Create a default FileBackend name.
310 // FileBackendGroup will register a default, if absent from $wgFileBackends.
311 $wgLocalFileRepo['backend'] = $wgLocalFileRepo['name'] . '-backend';
312 }
313
314 /**
315 * Shortcuts for $wgForeignFileRepos
316 */
317 if ( $wgUseSharedUploads ) {
318 if ( $wgSharedUploadDBname ) {
319 $wgForeignFileRepos[] = [
320 'class' => ForeignDBRepo::class,
321 'name' => 'shared',
322 'directory' => $wgSharedUploadDirectory,
323 'url' => $wgSharedUploadPath,
324 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
325 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
326 'transformVia404' => !$wgGenerateThumbnailOnParse,
327 'dbType' => $wgDBtype,
328 'dbServer' => $wgDBserver,
329 'dbUser' => $wgDBuser,
330 'dbPassword' => $wgDBpassword,
331 'dbName' => $wgSharedUploadDBname,
332 'dbFlags' => ( $wgDebugDumpSql ? DBO_DEBUG : 0 ) | DBO_DEFAULT,
333 'tablePrefix' => $wgSharedUploadDBprefix,
334 'hasSharedCache' => $wgCacheSharedUploads,
335 'descBaseUrl' => $wgRepositoryBaseUrl,
336 'fetchDescription' => $wgFetchCommonsDescriptions,
337 ];
338 } else {
339 $wgForeignFileRepos[] = [
340 'class' => FileRepo::class,
341 'name' => 'shared',
342 'directory' => $wgSharedUploadDirectory,
343 'url' => $wgSharedUploadPath,
344 'hashLevels' => $wgHashedSharedUploadDirectory ? 2 : 0,
345 'thumbScriptUrl' => $wgSharedThumbnailScriptPath,
346 'transformVia404' => !$wgGenerateThumbnailOnParse,
347 'descBaseUrl' => $wgRepositoryBaseUrl,
348 'fetchDescription' => $wgFetchCommonsDescriptions,
349 ];
350 }
351 }
352 if ( $wgUseInstantCommons ) {
353 $wgForeignFileRepos[] = [
354 'class' => ForeignAPIRepo::class,
355 'name' => 'wikimediacommons',
356 'apibase' => 'https://commons.wikimedia.org/w/api.php',
357 'url' => 'https://upload.wikimedia.org/wikipedia/commons',
358 'thumbUrl' => 'https://upload.wikimedia.org/wikipedia/commons/thumb',
359 'hashLevels' => 2,
360 'transformVia404' => true,
361 'fetchDescription' => true,
362 'descriptionCacheExpiry' => 43200,
363 'apiThumbCacheExpiry' => 0,
364 ];
365 }
366 foreach ( $wgForeignFileRepos as &$repo ) {
367 if ( !isset( $repo['directory'] ) && $repo['class'] === ForeignAPIRepo::class ) {
368 $repo['directory'] = $wgUploadDirectory; // b/c
369 }
370 if ( !isset( $repo['backend'] ) ) {
371 $repo['backend'] = $repo['name'] . '-backend';
372 }
373 }
374 unset( $repo ); // no global pollution; destroy reference
375
376 $rcMaxAgeDays = $wgRCMaxAge / ( 3600 * 24 );
377 // Ensure that default user options are not invalid, since that breaks Special:Preferences
378 $wgDefaultUserOptions['rcdays'] = min(
379 $wgDefaultUserOptions['rcdays'],
380 ceil( $rcMaxAgeDays )
381 );
382 $wgDefaultUserOptions['watchlistdays'] = min(
383 $wgDefaultUserOptions['watchlistdays'],
384 ceil( $rcMaxAgeDays )
385 );
386 unset( $rcMaxAgeDays );
387
388 if ( $wgSkipSkin ) {
389 // Hard deprecated in 1.34.
390 wfDeprecated( '$wgSkipSkin – use $wgSkipSkins instead', '1.23' );
391 $wgSkipSkins[] = $wgSkipSkin;
392 }
393
394 $wgSkipSkins[] = 'fallback';
395 $wgSkipSkins[] = 'apioutput';
396
397 if ( $wgLocalInterwiki ) {
398 // Hard deprecated in 1.34.
399 wfDeprecated( '$wgLocalInterwiki – use $wgLocalInterwikis instead', '1.23' );
400 // @phan-suppress-next-line PhanUndeclaredVariableDim
401 array_unshift( $wgLocalInterwikis, $wgLocalInterwiki );
402 }
403
404 // Set default shared prefix
405 if ( $wgSharedPrefix === false ) {
406 $wgSharedPrefix = $wgDBprefix;
407 }
408
409 // Set default shared schema
410 if ( $wgSharedSchema === false ) {
411 $wgSharedSchema = $wgDBmwschema;
412 }
413
414 if ( !$wgCookiePrefix ) {
415 if ( $wgSharedDB && $wgSharedPrefix && in_array( 'user', $wgSharedTables ) ) {
416 $wgCookiePrefix = $wgSharedDB . '_' . $wgSharedPrefix;
417 } elseif ( $wgSharedDB && in_array( 'user', $wgSharedTables ) ) {
418 $wgCookiePrefix = $wgSharedDB;
419 } elseif ( $wgDBprefix ) {
420 $wgCookiePrefix = $wgDBname . '_' . $wgDBprefix;
421 } else {
422 $wgCookiePrefix = $wgDBname;
423 }
424 }
425 $wgCookiePrefix = strtr( $wgCookiePrefix, '=,; +."\'\\[', '__________' );
426
427 if ( $wgEnableEmail ) {
428 $wgUseEnotif = $wgEnotifUserTalk || $wgEnotifWatchlist;
429 } else {
430 // Disable all other email settings automatically if $wgEnableEmail
431 // is set to false. - T65678
432 $wgAllowHTMLEmail = false;
433 $wgEmailAuthentication = false; // do not require auth if you're not sending email anyway
434 $wgEnableUserEmail = false;
435 $wgEnotifFromEditor = false;
436 $wgEnotifImpersonal = false;
437 $wgEnotifMaxRecips = 0;
438 $wgEnotifMinorEdits = false;
439 $wgEnotifRevealEditorAddress = false;
440 $wgEnotifUseRealName = false;
441 $wgEnotifUserTalk = false;
442 $wgEnotifWatchlist = false;
443 unset( $wgGroupPermissions['user']['sendemail'] );
444 $wgUseEnotif = false;
445 $wgUserEmailUseReplyTo = false;
446 $wgUsersNotifiedOnAllChanges = [];
447 }
448
449 if ( $wgMetaNamespace === false ) {
450 $wgMetaNamespace = str_replace( ' ', '_', $wgSitename );
451 }
452
453 // Default value is 2000 or the suhosin limit if it is between 1 and 2000
454 if ( $wgResourceLoaderMaxQueryLength === false ) {
455 $suhosinMaxValueLength = (int)ini_get( 'suhosin.get.max_value_length' );
456 if ( $suhosinMaxValueLength > 0 && $suhosinMaxValueLength < 2000 ) {
457 $wgResourceLoaderMaxQueryLength = $suhosinMaxValueLength;
458 } else {
459 $wgResourceLoaderMaxQueryLength = 2000;
460 }
461 unset( $suhosinMaxValueLength );
462 }
463
464 // Ensure the minimum chunk size is less than PHP upload limits or the maximum
465 // upload size.
466 $wgMinUploadChunkSize = min(
467 $wgMinUploadChunkSize,
468 UploadBase::getMaxUploadSize( 'file' ),
469 UploadBase::getMaxPhpUploadSize(),
470 ( wfShorthandToInteger(
471 ini_get( 'post_max_size' ) ?: ini_get( 'hhvm.server.max_post_size' ),
472 PHP_INT_MAX
473 ) ?: PHP_INT_MAX ) - 1024 // Leave some room for other POST parameters
474 );
475
476 /**
477 * Definitions of the NS_ constants are in Defines.php
478 * @private
479 */
480 $wgCanonicalNamespaceNames = NamespaceInfo::$canonicalNames;
481
482 /// @todo UGLY UGLY
483 if ( is_array( $wgExtraNamespaces ) ) {
484 $wgCanonicalNamespaceNames += $wgExtraNamespaces;
485 }
486
487 // Hard-deprecate setting $wgDummyLanguageCodes in LocalSettings.php
488 if ( count( $wgDummyLanguageCodes ) !== 0 ) {
489 wfDeprecated( '$wgDummyLanguageCodes', '1.29' );
490 }
491 // Merge in the legacy language codes, incorporating overrides from the config
492 $wgDummyLanguageCodes += [
493 // Internal language codes of the private-use area which get mapped to
494 // themselves.
495 'qqq' => 'qqq', // Used for message documentation
496 'qqx' => 'qqx', // Used for viewing message keys
497 ] + $wgExtraLanguageCodes + LanguageCode::getDeprecatedCodeMapping();
498 // Merge in (inverted) BCP 47 mappings
499 foreach ( LanguageCode::getNonstandardLanguageCodeMapping() as $code => $bcp47 ) {
500 $bcp47 = strtolower( $bcp47 ); // force case-insensitivity
501 if ( !isset( $wgDummyLanguageCodes[$bcp47] ) ) {
502 $wgDummyLanguageCodes[$bcp47] = $wgDummyLanguageCodes[$code] ?? $code;
503 }
504 }
505
506 // These are now the same, always
507 // To determine the user language, use $wgLang->getCode()
508 $wgContLanguageCode = $wgLanguageCode;
509
510 // Temporary backwards-compatibility reading of old Squid-named CDN settings as of MediaWiki 1.34,
511 // to support sysadmins who fail to update their settings immediately:
512
513 if ( isset( $wgUseSquid ) ) {
514 // If the sysadmin is still setting a value of $wgUseSquid to true but $wgUseCdn is the default of
515 // false, to be safe, assume they do want this still, so enable it.
516 if ( !$wgUseCdn && $wgUseSquid ) {
517 $wgUseCdn = $wgUseSquid;
518 wfDeprecated( '$wgUseSquid enabled but $wgUseCdn disabled; enabling CDN functions', '1.34' );
519 }
520 } else {
521 // Backwards-compatibility for extensions that read this value.
522 $wgUseSquid = $wgUseCdn;
523 }
524
525 if ( isset( $wgSquidServers ) ) {
526 // If the sysadmin is still setting a value of $wgSquidServers but $wgCdnServers is the default of
527 // empty, to be safe, assume they do want these servers to be still used, so use them.
528 if ( !empty( $wgSquidServers ) && empty( $wgCdnServers ) ) {
529 $wgCdnServers = $wgSquidServers;
530 wfDeprecated( '$wgSquidServers set, $wgCdnServers empty; using them', '1.34' );
531 }
532 } else {
533 // Backwards-compatibility for extensions that read this value.
534 $wgSquidServers = $wgCdnServers;
535 }
536
537 if ( isset( $wgSquidServersNoPurge ) ) {
538 // If the sysadmin is still setting values in $wgSquidServersNoPurge but $wgCdnServersNoPurge is
539 // the default of empty, to be safe, assume they do want these servers to be still used, so use
540 // them.
541 if ( !empty( $wgSquidServersNoPurge ) && empty( $wgCdnServersNoPurge ) ) {
542 $wgCdnServersNoPurge = $wgSquidServersNoPurge;
543 wfDeprecated( '$wgSquidServersNoPurge set, $wgCdnServersNoPurge empty; using them', '1.34' );
544 }
545 } else {
546 // Backwards-compatibility for extensions that read this value.
547 $wgSquidServersNoPurge = $wgCdnServersNoPurge;
548 }
549
550 if ( isset( $wgSquidMaxage ) ) {
551 // If the sysadmin is still setting a value of $wgSquidMaxage and it's higher than $wgCdnMaxAge,
552 // to be safe, assume they want the higher (lower performance requirement) value, so use that.
553 if ( $wgCdnMaxAge < $wgSquidMaxage ) {
554 $wgCdnMaxAge = $wgSquidMaxage;
555 wfDeprecated( '$wgSquidMaxage set higher than $wgCdnMaxAge; using the higher value', '1.34' );
556 }
557 } else {
558 // Backwards-compatibility for extensions that read this value.
559 $wgSquidMaxage = $wgCdnMaxAge;
560 }
561
562 // Easy to forget to falsify $wgDebugToolbar for static caches.
563 // If file cache or CDN cache is on, just disable this (DWIMD).
564 if ( $wgUseFileCache || $wgUseCdn ) {
565 $wgDebugToolbar = false;
566 }
567
568 // Blacklisted file extensions shouldn't appear on the "allowed" list
569 $wgFileExtensions = array_values( array_diff( $wgFileExtensions, $wgFileBlacklist ) );
570
571 if ( $wgInvalidateCacheOnLocalSettingsChange ) {
572 Wikimedia\suppressWarnings();
573 $wgCacheEpoch = max( $wgCacheEpoch, gmdate( 'YmdHis', filemtime( "$IP/LocalSettings.php" ) ) );
574 Wikimedia\restoreWarnings();
575 }
576
577 if ( $wgNewUserLog ) {
578 // Add new user log type
579 $wgLogTypes[] = 'newusers';
580 $wgLogNames['newusers'] = 'newuserlogpage';
581 $wgLogHeaders['newusers'] = 'newuserlogpagetext';
582 $wgLogActionsHandlers['newusers/newusers'] = NewUsersLogFormatter::class;
583 $wgLogActionsHandlers['newusers/create'] = NewUsersLogFormatter::class;
584 $wgLogActionsHandlers['newusers/create2'] = NewUsersLogFormatter::class;
585 $wgLogActionsHandlers['newusers/byemail'] = NewUsersLogFormatter::class;
586 $wgLogActionsHandlers['newusers/autocreate'] = NewUsersLogFormatter::class;
587 }
588
589 if ( $wgPageCreationLog ) {
590 // Add page creation log type
591 $wgLogTypes[] = 'create';
592 $wgLogActionsHandlers['create/create'] = LogFormatter::class;
593 }
594
595 if ( $wgPageLanguageUseDB ) {
596 $wgLogTypes[] = 'pagelang';
597 $wgLogActionsHandlers['pagelang/pagelang'] = PageLangLogFormatter::class;
598 }
599
600 if ( $wgCookieSecure === 'detect' ) {
601 $wgCookieSecure = ( WebRequest::detectProtocol() === 'https' );
602 }
603
604 if ( $wgProfileOnly ) {
605 // Hard deprecated in 1.34.
606 wfDeprecated(
607 '$wgProfileOnly set the log file in $wgDebugLogGroups[\'profileoutput\'] instead',
608 '1.23'
609 );
610 $wgDebugLogGroups['profileoutput'] = $wgDebugLogFile;
611 $wgDebugLogFile = '';
612 }
613
614 // Backwards compatibility with old password limits
615 if ( $wgMinimalPasswordLength !== false ) {
616 $wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = $wgMinimalPasswordLength;
617 }
618
619 if ( $wgMaximalPasswordLength !== false ) {
620 $wgPasswordPolicy['policies']['default']['MaximalPasswordLength'] = $wgMaximalPasswordLength;
621 }
622
623 if ( $wgPHPSessionHandling !== 'enable' &&
624 $wgPHPSessionHandling !== 'warn' &&
625 $wgPHPSessionHandling !== 'disable'
626 ) {
627 $wgPHPSessionHandling = 'warn';
628 }
629 if ( defined( 'MW_NO_SESSION' ) ) {
630 // If the entry point wants no session, force 'disable' here unless they
631 // specifically set it to the (undocumented) 'warn'.
632 $wgPHPSessionHandling = MW_NO_SESSION === 'warn' ? 'warn' : 'disable';
633 }
634
635 // Disable MWDebug for command line mode, this prevents MWDebug from eating up
636 // all the memory from logging SQL queries on maintenance scripts
637 global $wgCommandLineMode;
638 if ( $wgDebugToolbar && !$wgCommandLineMode ) {
639 MWDebug::init();
640 }
641
642 // Reset the global service locator, so any services that have already been created will be
643 // re-created while taking into account any custom settings and extensions.
644 MediaWikiServices::resetGlobalInstance( new GlobalVarConfig(), 'quick' );
645
646 // Define a constant that indicates that the bootstrapping of the service locator
647 // is complete.
648 define( 'MW_SERVICE_BOOTSTRAP_COMPLETE', 1 );
649
650 MWExceptionHandler::installHandler();
651
652 // T48998: Bail out early if $wgArticlePath is non-absolute
653 foreach ( [ 'wgArticlePath', 'wgVariantArticlePath' ] as $varName ) {
654 if ( $$varName && !preg_match( '/^(https?:\/\/|\/)/', $$varName ) ) {
655 throw new FatalError(
656 "If you use a relative URL for \$$varName, it must start " .
657 'with a slash (<code>/</code>).<br><br>See ' .
658 "<a href=\"https://www.mediawiki.org/wiki/Manual:\$$varName\">" .
659 "https://www.mediawiki.org/wiki/Manual:\$$varName</a>."
660 );
661 }
662 }
663
664 if ( $wgCanonicalServer === false ) {
665 $wgCanonicalServer = wfExpandUrl( $wgServer, PROTO_HTTP );
666 }
667
668 // Set server name
669 $serverParts = wfParseUrl( $wgCanonicalServer );
670 if ( $wgServerName !== false ) {
671 wfWarn( '$wgServerName should be derived from $wgCanonicalServer, '
672 . 'not customized. Overwriting $wgServerName.' );
673 }
674 $wgServerName = $serverParts['host'];
675 unset( $serverParts );
676
677 // Set defaults for configuration variables
678 // that are derived from the server name by default
679 // Note: $wgEmergencyContact and $wgPasswordSender may be false or empty string (T104142)
680 if ( !$wgEmergencyContact ) {
681 $wgEmergencyContact = 'wikiadmin@' . $wgServerName;
682 }
683 if ( !$wgPasswordSender ) {
684 $wgPasswordSender = 'apache@' . $wgServerName;
685 }
686 if ( !$wgNoReplyAddress ) {
687 $wgNoReplyAddress = $wgPasswordSender;
688 }
689
690 if ( $wgSecureLogin && substr( $wgServer, 0, 2 ) !== '//' ) {
691 $wgSecureLogin = false;
692 wfWarn( 'Secure login was enabled on a server that only supports '
693 . 'HTTP or HTTPS. Disabling secure login.' );
694 }
695
696 $wgVirtualRestConfig['global']['domain'] = $wgCanonicalServer;
697
698 // Now that GlobalFunctions is loaded, set defaults that depend on it.
699 if ( $wgTmpDirectory === false ) {
700 $wgTmpDirectory = wfTempDir();
701 }
702
703 // We don't use counters anymore. Left here for extensions still
704 // expecting this to exist. Should be removed sometime 1.26 or later.
705 if ( !isset( $wgDisableCounters ) ) {
706 $wgDisableCounters = true;
707 }
708
709 if ( $wgMainWANCache === false ) {
710 // Setup a WAN cache from $wgMainCacheType with no relayer.
711 // Sites using multiple datacenters can configure a relayer.
712 $wgMainWANCache = 'mediawiki-main-default';
713 $wgWANObjectCaches[$wgMainWANCache] = [
714 'class' => WANObjectCache::class,
715 'cacheId' => $wgMainCacheType
716 ];
717 }
718
719 if ( $wgSharedDB && $wgSharedTables ) {
720 // Apply $wgSharedDB table aliases for the local LB (all non-foreign DB connections)
721 MediaWikiServices::getInstance()->getDBLoadBalancer()->setTableAliases(
722 array_fill_keys(
723 $wgSharedTables,
724 [
725 'dbname' => $wgSharedDB,
726 'schema' => $wgSharedSchema,
727 'prefix' => $wgSharedPrefix
728 ]
729 )
730 );
731 }
732
733 // Raise the memory limit if it's too low
734 // Note, this makes use of wfDebug, and thus should not be before
735 // MWDebug::init() is called.
736 wfMemoryLimit( $wgMemoryLimit );
737
738 /**
739 * Set up the timezone, suppressing the pseudo-security warning in PHP 5.1+
740 * that happens whenever you use a date function without the timezone being
741 * explicitly set. Inspired by phpMyAdmin's treatment of the problem.
742 */
743 if ( is_null( $wgLocaltimezone ) ) {
744 Wikimedia\suppressWarnings();
745 $wgLocaltimezone = date_default_timezone_get();
746 Wikimedia\restoreWarnings();
747 }
748
749 date_default_timezone_set( $wgLocaltimezone );
750 if ( is_null( $wgLocalTZoffset ) ) {
751 $wgLocalTZoffset = date( 'Z' ) / 60;
752 }
753 // The part after the System| is ignored, but rest of MW fills it
754 // out as the local offset.
755 $wgDefaultUserOptions['timecorrection'] = "System|$wgLocalTZoffset";
756
757 if ( !$wgDBerrorLogTZ ) {
758 $wgDBerrorLogTZ = $wgLocaltimezone;
759 }
760
761 // Initialize the request object in $wgRequest
762 $wgRequest = RequestContext::getMain()->getRequest(); // BackCompat
763 // Set user IP/agent information for agent session consistency purposes
764 $cpPosInfo = LBFactory::getCPInfoFromCookieValue(
765 // The cookie has no prefix and is set by MediaWiki::preOutputCommit()
766 $wgRequest->getCookie( 'cpPosIndex', '' ),
767 // Mitigate broken client-side cookie expiration handling (T190082)
768 time() - ChronologyProtector::POSITION_COOKIE_TTL
769 );
770 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->setRequestInfo( [
771 'IPAddress' => $wgRequest->getIP(),
772 'UserAgent' => $wgRequest->getHeader( 'User-Agent' ),
773 'ChronologyProtection' => $wgRequest->getHeader( 'MediaWiki-Chronology-Protection' ),
774 'ChronologyPositionIndex' => $wgRequest->getInt( 'cpPosIndex', $cpPosInfo['index'] ),
775 'ChronologyClientId' => $cpPosInfo['clientId']
776 ?? $wgRequest->getHeader( 'MediaWiki-Chronology-Client-Id' )
777 ] );
778 unset( $cpPosInfo );
779 // Make sure that object caching does not undermine the ChronologyProtector improvements
780 if ( $wgRequest->getCookie( 'UseDC', '' ) === 'master' ) {
781 // The user is pinned to the primary DC, meaning that they made recent changes which should
782 // be reflected in their subsequent web requests. Avoid the use of interim cache keys because
783 // they use a blind TTL and could be stale if an object changes twice in a short time span.
784 MediaWikiServices::getInstance()->getMainWANObjectCache()->useInterimHoldOffCaching( false );
785 }
786
787 // Useful debug output
788 if ( $wgCommandLineMode ) {
789 if ( isset( $self ) ) {
790 wfDebug( "\n\nStart command line script $self\n" );
791 }
792 } else {
793 $debug = "\n\nStart request {$wgRequest->getMethod()} {$wgRequest->getRequestURL()}\n";
794 $debug .= "HTTP HEADERS:\n";
795 foreach ( $wgRequest->getAllHeaders() as $name => $value ) {
796 $debug .= "$name: $value\n";
797 }
798 wfDebug( $debug );
799 }
800
801 $wgMemc = ObjectCache::getLocalClusterInstance();
802 $messageMemc = wfGetMessageCacheStorage();
803
804 // Most of the config is out, some might want to run hooks here.
805 Hooks::run( 'SetupAfterCache' );
806
807 /**
808 * @var Language $wgContLang
809 * @deprecated since 1.32, use the ContentLanguage service directly
810 */
811 $wgContLang = MediaWikiServices::getInstance()->getContentLanguage();
812
813 // Now that variant lists may be available...
814 $wgRequest->interpolateTitle();
815
816 /**
817 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
818 * session ID (if any) loaded at startup
819 */
820 $wgInitialSessionId = null;
821 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
822 // If session.auto_start is there, we can't touch session name
823 if ( $wgPHPSessionHandling !== 'disable' && !wfIniGetBool( 'session.auto_start' ) ) {
824 session_name( $wgSessionName ?: $wgCookiePrefix . '_session' );
825 }
826
827 // Create the SessionManager singleton and set up our session handler,
828 // unless we're specifically asked not to.
829 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
830 MediaWiki\Session\PHPSessionHandler::install(
831 MediaWiki\Session\SessionManager::singleton()
832 );
833 }
834
835 // Initialize the session
836 try {
837 $session = MediaWiki\Session\SessionManager::getGlobalSession();
838 } catch ( OverflowException $ex ) {
839 if ( isset( $ex->sessionInfos ) && count( $ex->sessionInfos ) >= 2 ) {
840 // The exception is because the request had multiple possible
841 // sessions tied for top priority. Report this to the user.
842 $list = [];
843 foreach ( $ex->sessionInfos as $info ) {
844 $list[] = $info->getProvider()->describe( $wgContLang );
845 }
846 $list = $wgContLang->listToText( $list );
847 throw new HttpError( 400,
848 Message::newFromKey( 'sessionmanager-tie', $list )->inLanguage( $wgContLang )->plain()
849 );
850 }
851
852 // Not the one we want, rethrow
853 throw $ex;
854 }
855
856 if ( $session->isPersistent() ) {
857 $wgInitialSessionId = $session->getSessionId();
858 }
859
860 $session->renew();
861 if ( MediaWiki\Session\PHPSessionHandler::isEnabled() &&
862 ( $session->isPersistent() || $session->shouldRememberUser() ) &&
863 session_id() !== $session->getId()
864 ) {
865 // Start the PHP-session for backwards compatibility
866 if ( session_id() !== '' ) {
867 wfDebugLog( 'session', 'PHP session {old_id} was already started, changing to {new_id}', 'all', [
868 'old_id' => session_id(),
869 'new_id' => $session->getId(),
870 ] );
871 session_write_close();
872 }
873 session_id( $session->getId() );
874 session_start();
875 }
876
877 unset( $session );
878 } else {
879 // Even if we didn't set up a global Session, still install our session
880 // handler unless specifically requested not to.
881 if ( !defined( 'MW_NO_SESSION_HANDLER' ) ) {
882 MediaWiki\Session\PHPSessionHandler::install(
883 MediaWiki\Session\SessionManager::singleton()
884 );
885 }
886 }
887
888 /**
889 * @var User $wgUser
890 */
891 $wgUser = RequestContext::getMain()->getUser(); // BackCompat
892
893 /**
894 * @var Language $wgLang
895 */
896 $wgLang = new StubUserLang;
897
898 /**
899 * @var OutputPage $wgOut
900 */
901 $wgOut = RequestContext::getMain()->getOutput(); // BackCompat
902
903 /**
904 * @var Parser $wgParser
905 * @deprecated since 1.32, use MediaWikiServices::getInstance()->getParser() instead
906 */
907 $wgParser = new StubObject( 'wgParser', function () {
908 return MediaWikiServices::getInstance()->getParser();
909 } );
910
911 /**
912 * @var Title $wgTitle
913 */
914 $wgTitle = null;
915
916 // Extension setup functions
917 // Entries should be added to this variable during the inclusion
918 // of the extension file. This allows the extension to perform
919 // any necessary initialisation in the fully initialised environment
920 foreach ( $wgExtensionFunctions as $func ) {
921 call_user_func( $func );
922 }
923
924 // If the session user has a 0 id but a valid name, that means we need to
925 // autocreate it.
926 if ( !defined( 'MW_NO_SESSION' ) && !$wgCommandLineMode ) {
927 $sessionUser = MediaWiki\Session\SessionManager::getGlobalSession()->getUser();
928 if ( $sessionUser->getId() === 0 && User::isValidUserName( $sessionUser->getName() ) ) {
929 $res = MediaWiki\Auth\AuthManager::singleton()->autoCreateUser(
930 $sessionUser,
931 MediaWiki\Auth\AuthManager::AUTOCREATE_SOURCE_SESSION,
932 true
933 );
934 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Autocreation attempt', [
935 'event' => 'autocreate',
936 'status' => $res,
937 ] );
938 unset( $res );
939 }
940 unset( $sessionUser );
941 }
942
943 if ( !$wgCommandLineMode ) {
944 Pingback::schedulePingback();
945 }
946
947 $wgFullyInitialised = true;